<?php
namespace app\apijson\query\operators;

class OrderOperator
{
    public static function apply($query, $value)
    {
        $orders = explode(',', $value);
        foreach ($orders as $order) {
            $order = trim($order);
            if (substr($order, -1) === '-') {
                $field = substr($order, 0, -1);
                if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*]*$/', $field)) {
                    throw new \app\apijson\core\ApiJsonException('非法排序字段: ' . $field);
                }
                $query->orderBy($field, 'desc');
            } else {
                $field = rtrim($order, '+');
                if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.*]*$/', $field)) {
                    throw new \app\apijson\core\ApiJsonException('非法排序字段: ' . $field);
                }
                $query->orderBy($field, 'asc');
            }
        }
    }
} 